package com.waitingsnow.common.share
{
import com.waitingsnow.common.share.BaseShare;
import com.waitingsnow.common.share.config.AppInfo;
import com.waitingsnow.common.share.config.FacebookURLDefaults;
import com.waitingsnow.common.share.events.ShareEvent;
import com.waitingsnow.common.share.util.UploadPostHelper;
import com.waitingsnow.core.debug.Logger;
import com.waitingsnow.core.service.CookieService;
import com.waitingsnow.core.util.core.ExternalUtil;

import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.LocationChangeEvent;
import flash.media.StageWebView;
import flash.net.SharedObject;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.utils.ByteArray;

/**
 * facebook分享 
 * @author NeilWang
 * 
 */
public class ShareToFaceBook extends BaseShare
{
	//==========================================================================
	//  Class variables
	//==========================================================================
	static private const FACEBOOK_COOKIE_NAME:String = "facebookCookName";
	static private const FACEBOOK_TOKEN:String = "access_token";
	
    //==========================================================================
    //  Constructor
    //==========================================================================
    /**
     * Constructs a new <code>ShareToFaceBook</code> instance.
     * 
     */
    public function ShareToFaceBook()
    {
        super();
        init();
    }
    
	//==========================================================================
	//  Variables
	//==========================================================================
    private var access_token:String;
    private var urlLoader:URLLoader;
    private var so:CookieService;
    
    //==========================================================================
    //  Methods
    //==========================================================================
    /**
     * 初始化 
     * @param parames
     * 
     */    
    private function init():void
    {
        checkToken();
    }
    
    /**
     * 分享 
     * @param message
     * @param picUrl
     * 
     */    
    override public function share(message:String = "", pic:ByteArray = null):void
    {
        urlLoader = new URLLoader();
        var url:String = FacebookURLDefaults.GRAPH_URL + "/me/photos";
        var urlRequest:URLRequest = new URLRequest(url);
        urlRequest.method = URLRequestMethod.POST;
        var urlv:URLVariables = new URLVariables();
        urlv.message = message;
        urlv.access_token = access_token;
        urlRequest.data = UploadPostHelper.getPostData(pic, urlv, "pic", UploadPostHelper.IMAGE_JPG);
        urlRequest.contentType = "multipart/form-data;" +"boundary=" +
                                        UploadPostHelper.getBoundary();
        urlLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        urlLoader.addEventListener(Event.COMPLETE, loadCompleteHandler);
        urlLoader.load(urlRequest);
    }
    
    /**
     * 先从缓存中获取应用ID和应用密钥
     */		
    override public function checkToken():void
    {
		if (!so)
		{
			so = new CookieService(FACEBOOK_COOKIE_NAME);
		}
        access_token = so.getProps(FACEBOOK_TOKEN);
        //判断是否已经授权
        if(access_token)
        {
            //已经被授权，直接获取数据
            _hasAuthorize = true;
            Logger.info("facebook账号已经被授权，直接获取数据");
        }
        else
        {
            //开始获取授权
            startAuth();
        }
    }
	
	override public function dispose():void
	{
		removeWebView();
		if (so)
		{
			so.dispose();
			so = null;
		}
		if (urlLoader)
		{
			urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			urlLoader.removeEventListener(Event.COMPLETE, loadCompleteHandler);
			urlLoader.close();
			urlLoader = null;
		}
		super.dispose();
	}

    /**
     * 授权
     * 
     */    
    private function startAuth():void
    {
		var authorURL:String = FacebookURLDefaults.AUTH_URL + "?"+ 
			formatData(AppInfo.FACEBOOK_APP_KEY, "touch", 
				AppInfo.FACEBOOK_PERMISSIONS);
		webView = new StageWebView();
		webView.stage = stage;
		webView.viewPort = area;
		webView.loadURL(authorURL);
		webView.addEventListener(Event.COMPLETE, webViewCompleteHandler);
		webView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, 
			webViewChangeHandler);
    }
    
    /**
     * 从地址上获取accessToken
     * @param url
     * 
     */    
    private function checkBackUrl(url:String):void
    {
        if (access_token)
        {
            return;
        }
        var location:String = webView.location;
        Logger.debug(location);
        if (location.indexOf(FacebookURLDefaults.LOGIN_FAIL_URL) == 0 ||
            location.indexOf(FacebookURLDefaults.LOGIN_FAIL_SECUREURL) == 0)
        {
			removeWebView();
        }
        else if (location.indexOf(FacebookURLDefaults.LOGIN_SUCCESS_URL) == 0 ||
            location.indexOf(FacebookURLDefaults.LOGIN_SUCCESS_SECUREURL) == 0)
        {
			removeWebView();
            var variables:URLVariables = ExternalUtil.getURLVariables(location);
            access_token = variables.access_token;
			so.setProps(FACEBOOK_TOKEN, access_token);
            dispatchEvent(new ShareEvent(ShareEvent.AUTHORIZE_COMPLETE));
        }
    }
	
	private function removeWebView():void
	{
		if (webView)
		{
			webView.removeEventListener(Event.COMPLETE, webViewCompleteHandler);
			webView.removeEventListener(LocationChangeEvent.LOCATION_CHANGE, 
				webViewChangeHandler);
			webView.dispose();
			webView=null;
		}
	}
    
    /**
     *  
     * @param applicationId
     * @param display
     * @param extendedPermissions
     * @return 
     * 
     */    
    private function formatData(applicationId:String, display:String, 
								extendedPermissions:Array = null):URLVariables 
	{
        var vars:URLVariables = new URLVariables();
        vars.client_id = applicationId;
        vars.redirect_uri = FacebookURLDefaults.LOGIN_SUCCESS_URL;
        vars.display = display;
        vars.type = 'user_agent';
        
        if (extendedPermissions != null) {
            vars.scope = extendedPermissions.join(',');
        }
        
        return vars;
    }
    
    //==========================================================================
    //  Event Handlers
    //==========================================================================
    private function webViewChangeHandler(event:LocationChangeEvent):void
    {
        checkBackUrl(webView.location);
    }
    
    private function webViewCompleteHandler(event:Event):void
    {
        checkBackUrl(webView.location);
    }
    
    private function loadCompleteHandler(event:Event):void
    {
		Logger.debug(urlLoader.data);
        dispatchEvent(new ShareEvent(ShareEvent.SHARE_COMPLETE));
    }
    
    private function ioErrorHandler(event:IOErrorEvent):void
    {
		Logger.error("分享IoError: " + event.toString());
    }
}
}